<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\MoneyLog;
use app\common\model\RechargeWithdrawal;
use think\Db;

class Pay extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 充值
     */
    public function recharge()
    {
        $userInfo = $this->auth->getUserinfo();
        
        if( $userInfo['hasIdExamine'] ){
            $this->error('请先设置实名信息再操作！');
        }
        if( empty($userInfo['bank_num'])  ){
            $this->error('请先绑定银行卡再操作！');
        }

        $money = $this->request->post('money');
        $username = $this->request->post('username');

        if( empty($username) ){
            $this->error('充值用户名必填');
        }

        if( $money <= 0 ){
            $this->error('充值金额错误');
        }


        $userInfo = $this->auth->getUser();
        RechargeWithdrawal::create([
            'user_id'=>$userInfo->id,
            'user_name'=>$username,
            'money'=>$money,
            'status'=>1,
            'type'=>1,
        ]);
        $this->success('充值申请成功，请等待工作人员审核！');
    }


    /**
     * 提现
     */
    public function withdrawal()
    {
        $payPwd = $this->request->post('payPwd');
        $money = $this->request->post('money');

        $userInfo = $this->auth->getUser();
        if( md5(md5($payPwd)) != $userInfo->pay_pwd ){
            $this->error('支付密码错误');
        }

        if( $money < 100 ){
            $this->error('提现金额必须大于100');
        }

        if( $money > $userInfo->money ){
            $this->error('余额不足');
        }

        if( empty($userInfo->real_name) ){
            $this->error('请先设置实名信息再提现！');
        }

        if( empty($userInfo->bank_num) || empty($userInfo->bank_sub_name) || empty($userInfo->bank_name) ){
            $this->error('请先设置银行卡信息再提现！');
        }


        Db::startTrans();
        try{
            //创建提现审核
            RechargeWithdrawal::create([
                'user_id'=>$userInfo->id,
                'money'=>$money,
                'status'=>1,
                'type'=>2,
            ]);
            //扣除余额
            //updateMoney($userInfo,-$money,'提现');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error('提现失败:'.$e->getMessage());
        }

        $this->success('提现申请成功，请等待工作人员审核');
    }

    /**
     * 获取金额变动
     */
    public function getLog($limit = 10,$page = 1)
    {
        $userInfo = $this->auth->getUser();
        $logList = MoneyLog::limit(($page-1)*$limit,$limit)
                                ->where('user_id',$userInfo->id)
                                ->order('id desc')
                                ->select();
        $accountBalance = number_format($userInfo->money,2);
        $this->success('获取成功',[
            'log_list'        => $logList,
            'account_balance' => $accountBalance
        ]);
    }


}